package userserv

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"log"
	"net/http"
	"rhelper"
	"strconv"
)

func replyError(w http.ResponseWriter, ec int) {
	w.Header().Set("error", fmt.Sprintf("%d", ec))
	w.Write(nil)
}

func replyErrorWithMsg(w http.ResponseWriter, ec int, errmsg string) {
	w.Header().Set("error", fmt.Sprintf("%d", ec))
	w.Header().Set("errmsg", errmsg)
	w.Write(nil)
}
func replyBuffer(w http.ResponseWriter, buf []byte) {
	w.Header().Add("Content-Length", strconv.Itoa(len(buf)))
	w.WriteHeader(200)
	w.Write(buf)
}

func replyJSON(w http.ResponseWriter, j interface{}) {
	buf, _ := json.Marshal(j)
	replyBuffer(w, buf)
}

func getHomeMemberUserIds(homeId string) ([]string, error) {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	HomeMemberUserIds, err := redis.Strings(rconn.Do("ZRANGE", rhelper.HomeMemberSet+homeId, "0", "-1"))
	if err != nil {
		log.Println("Read home member failed.", err)
		return nil, err
	}

	if len(HomeMemberUserIds) == 0 {
		return nil, errors.New("no home member")
	}

	ids := []string{}
	for _, v := range HomeMemberUserIds {
		ids = append(ids, v[4:])
	}
	return ids, nil
}
